package com.itzzj.common.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 自定义 Filter
 */
@Slf4j
@Component
public class MyFilter implements Filter {
    /**
     * 初始化过滤器后执行的操作
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("初始化过滤器：" + filterConfig.getFilterName());
    }

    /**
     * 对请求进行过滤
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("过滤器开始对请求进行预处理");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        log.info("请求的接口为：" + requestURI);
        long startTime = System.currentTimeMillis();
        // 通过 doFilter 方法实现过滤功能
        filterChain.doFilter(servletRequest, servletResponse);
        // 上面的 doFilter 方法执行完成后，用户的请求已近返回
        long endTime = System.currentTimeMillis();
        log.info("该用户的请求已经处理完毕，请求话费时间为：" + (endTime - startTime));
    }

    /**
     * 销毁过滤器后执行的操作，主要用户对某些资源的回收
     */
    @Override
    public void destroy() {
        log.info("销毁过滤器");
    }
}








































